package com.cnswhy.cloud.server.iot.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;

/**
 * 后台管理用户session拦截器
 * 
 * @author qiuxw
 *
 */
@Slf4j
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter
{
	
	

	@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {

        return super.preHandle(request, response, handler);
    }
	
	public static HashMap<String, String> getBody(HttpServletRequest request) throws IOException
	{
		
		HashMap<String, String> bodyMap = new HashMap<String, String>();

		StringBuilder stringBuilder = new StringBuilder();
		BufferedReader bufferedReader = null;

		try
		{
			InputStream inputStream = request.getInputStream();
			if (inputStream != null)
			{
				bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
				char[] charBuffer = new char[128];
				int bytesRead = -1;
				while ((bytesRead = bufferedReader.read(charBuffer)) > 0)
				{
					stringBuilder.append(charBuffer, 0, bytesRead);
					String[] paramsArr = stringBuilder.toString().split("=");
					bodyMap.put(paramsArr[0], paramsArr[1]);
				}
			}
			else
			{
				stringBuilder.append("");
			}
		}
		catch (IOException ex)
		{
			throw ex;
		}
		finally
		{
			if (bufferedReader != null)
			{
				try
				{
					bufferedReader.close();
				}
				catch (IOException ex)
				{
					throw ex;
				}
			}
		}
		
		return bodyMap;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception
	{
		super.postHandle(request, response, handler, modelAndView);
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception
	{
		// TODO Auto-generated method stub
		super.afterCompletion(request, response, handler, ex);
	}
}
